<?php

namespace common\behavior\CommonMessagePushing;


use common\model\ReviewRequestNodeModel;
use common\model\VersionModel;
use Webman\Stomp\Client;

/**
 * 任务提交审核行为 消息通知
 */
class TaskReviewV2Behavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        if (($params['type'] ?? 'default') !== 'commit_version') {
            return;
        }
        $params = $params['data'];
        $version = model(VersionModel::class)->find($params['version_id']);
        if (empty($version) || module_by_id($version['module_id'])['code'] !== 'task') {
            return;
        }
        $receiver = $params['receiver'] ?? [];
        if (empty($receiver)) {
            // 获取审核下所有已启用待审核节点，填充消息通知人
            $reviewRequestNodeList = model(ReviewRequestNodeModel::class)->where([
                'review_request_id' => $params['review_request_id'],
                'is_reviewed' => 'no',
                'is_active' => 'yes'
            ])->select();
            $receiver = array_map(fn($node) => [
                'user_id' => $node['plan_reviewer'],
                'role' => 'plan_reviewer',
            ], $reviewRequestNodeList);
        }
        // 组装消息包
        $data = [
            'source_user_id' => $params['user_id'] ?? \request()->getUserId(),
            'time' => $params['time'] ?? time(),
            'source_id' => $version['link_id'],
            'source_module_code' => 'task',
            'category' => 'task_review',
            'receiver' => $receiver,
            'receiver_cc' => [],
        ];
        try {
            trace("common task review push behavior" . request()->getUnionUserId(), 'DEBUG');
            Client::send('common_message_pushing', build_queue_data_with_xu($data));
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
        return;
    }
}
